package com.db.protocol.message;

import com.db.protocol.tags.MsgType;
import com.db.protocol.tags.OrderSide;
import com.db.protocol.tags.Tag;

import java.util.HashMap;

/**
 * @author nulls.narik
 */
public abstract class AbstractMessage extends HashMap<Tag, Object> {

    protected static final String SPLIT_PAIR = "|";

    protected static final String SPLIT_KEY_AND_VALUE = "=";

    protected StringBuilder newMsg(MsgType type) {
        StringBuilder message = new StringBuilder();
        return message.append(Tag.MSG_TYPE.value()).append(SPLIT_KEY_AND_VALUE).append(type.value());
    }

    protected StringBuilder addPair(StringBuilder msg, Tag key, String value) {
        return msg.append(SPLIT_PAIR).append(key.value()).append(SPLIT_KEY_AND_VALUE).append(value);
    }

    // TODO: без класса Price
    protected String floatToString(float value) {
        return String.format("%.3f", value);
    }

    @Override
    public String toString() {
        StringBuilder message = newMsg((MsgType) get(Tag.MSG_TYPE));
        for (Tag tag : keySet()) {
            Object value =  get(tag);
            switch (tag) {
                case CLIENT_ID:
                    message = addPair(message, tag, value.toString());
                    break;
                case EXCHANGE_ID:
                    message = addPair(message, tag, value.toString());
                    break;
                case ORDER_SIDE:
                    message = addPair(message, tag, String.valueOf(((OrderSide)value).value()));
                    break;
                case TICKER_SYMBOL:
                    message = addPair(message, tag, value.toString());
                    break;
                case PRICE:
                    message = addPair(message, tag, floatToString((Float)value));
                    break;
                case QUANTITY:
                    message = addPair(message, tag, value.toString());
                    break;
            }
        }
        return message.toString();
    }

}
